package com.learning.spring.cloud.alibaba.hystrix.detail.rxjava;

import rx.Observable;
import rx.Single;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * ClassName: RxJavaDemo
 * Description: RxJava 简单 Demo
 * Date: 2021/7/25 23:03 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class RxJavaDemo {

    public static void main(String[] args) throws InterruptedException {

        // 事件发布和订阅
        Single.just(new Action1().init())
                .subscribeOn(Schedulers.newThread())
                .subscribe(RxJavaDemo::println);

        //
        Single.fromCallable(
                new Callable<String>() {
                    @Override
                    public String call() throws Exception {
                        return "ok1";
                    }
                }
        ).subscribeOn(Schedulers.io())
                .subscribe(RxJavaDemo::isOk);

        //
        observeremo();

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    public static class Action1 {

        public String init() {
            return "事件1发布";
        }
    }

    public static void println(Object value) {
        // 我们可以通过 rxjava 订阅拿到在某一个事件进行发布时的 value
        System.out.printf("[线程: %s] 数据: %s\n", Thread.currentThread().getName(), value);

    }

    public static void isOk(Object val) {
        if (val.equals("ok")) {
            System.out.println("执行了XXXX");
        } else {
            System.out.println("不通过");
        }
    }

    public static void observeremo() throws InterruptedException {
        List<Integer> valueList = Arrays.asList(1, 2, 3, 4);
        Observable.from(valueList).
                subscribe(
                        new rx.functions.Action1<Integer>() {
                            @Override
                            public void call(Integer next) {
                                if (next > 2) {
                                    throw new IllegalArgumentException("非法参数");
                                }
                                System.out.println("处理数据" + next);
                            }
                        },
                        new rx.functions.Action1<Throwable>() {
                            @Override
                            public void call(Throwable error) {
                                System.out.println("降级!!");
                            }
                        },
                        new Action0() {
                            @Override
                            public void call() {
                                System.out.println("执行完毕");
                            }
                        }
                );

    }
}
